// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Card, Descriptions, Tag, message } from 'antd';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 路由和状态管理
import { useParams } from '@umijs/max';

// 6. 工具库
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserRoleAssignment } from '@/services/generated';

const UserRoleDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [data, setData] = useState<UserRoleAssignment | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        await autoLoginInDev();
        const response = await apiClients.permissions.permissionsUserRolesRetrieve({ id: parseInt(id!) });
        setData(response.data);
      } catch (error) {
        message.error('获取失败');
      } finally {
        setLoading(false);
      }
    };
    if (id) fetchData();
  }, [id]);

  const getStatusTag = (status: any, expiresAt: any) => {
    let color = 'red';
    let statusText = '未知';
    
    if (status === 'active') {
      // 检查是否过期
      if (expiresAt && expiresAt !== null && expiresAt !== '') {
        try {
          const expiresDate = dayjs(String(expiresAt));
          if (expiresDate.isValid() && expiresDate.isBefore(dayjs())) {
            color = 'orange';
            statusText = '已过期';
          } else {
            color = 'green';
            statusText = '激活';
          }
        } catch (error) {
          color = 'green';
          statusText = '激活';
        }
      } else {
        color = 'green';
        statusText = '激活';
      }
    } else if (status === 'inactive') {
      color = 'red';
      statusText = '禁用';
    } else if (status === 'expired') {
      color = 'orange';
      statusText = '过期';
    }
    
    return <Tag color={color}>{statusText}</Tag>;
  };

  const formatExpiresAt = (expiresAt: any) => {
    if (!expiresAt || expiresAt === null || expiresAt === undefined || expiresAt === '') {
      return <span style={{ color: '#52c41a' }}>永不过期</span>;
    }
    try {
      const date = dayjs(String(expiresAt));
      if (!date.isValid()) {
        return <span style={{ color: '#52c41a' }}>永不过期</span>;
      }
      return date.format('YYYY-MM-DD HH:mm:ss');
    } catch (error) {
      return <span style={{ color: '#52c41a' }}>永不过期</span>;
    }
  };

  return (
    <PageContainer title="用户角色分配详情" loading={loading}>
      <Card>
        <Descriptions column={2}>
          <Descriptions.Item label="ID">{data?.id}</Descriptions.Item>
          <Descriptions.Item label="用户">
            <div>
              <div>{data?.user_username}</div>
              <div style={{ fontSize: '12px', color: '#666' }}>{data?.user_email}</div>
            </div>
          </Descriptions.Item>
          <Descriptions.Item label="角色">
            <Tag color="blue">{data?.role_name}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            {getStatusTag(data?.status, data?.expires_at)}
          </Descriptions.Item>
          <Descriptions.Item label="分配时间">
            {data?.assigned_at ? dayjs(data.assigned_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="过期时间">
            {formatExpiresAt(data?.expires_at)}
          </Descriptions.Item>
          <Descriptions.Item label="分配人">{data?.assigned_by_username}</Descriptions.Item>
          <Descriptions.Item label="分配原因" span={2}>{data?.reason}</Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {data?.created_at ? new Date(data.created_at).toLocaleString('zh-CN') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="更新时间">
            {data?.updated_at ? new Date(data.updated_at).toLocaleString('zh-CN') : '-'}
          </Descriptions.Item>
        </Descriptions>
        <div style={{ marginTop: 16 }}>
          <Button type="primary" href={`/permissions/user-roles/edit/${id}`}>编辑</Button>
          <Button style={{ marginLeft: 8 }} href="/permissions/user-roles">返回列表</Button>
        </div>
      </Card>
    </PageContainer>
  );
};

export default UserRoleDetail;
